<template>
  <div class="pages">
    <maps ref="mapsRef" @rectangle="mapsArr" :all-routes="allRoutes" @track-selected="onTrackSelected" />

    <div class="cener" style="width: 100%;">
      <headers />
    </div>
    <div class="cener" style="width: 300px;top:72px;left: 10px;">
      <userList ref="userListRef" @rtn="uRtn" @converted-data="getGps" @getGpsInfo="GpsInfo" @showMap="onTrackSelectedU"
                @play="play" @mapSetUser="group" :all-routes="allRoutes" />
    </div>
    <tip />
<!--    <trajectoryTime v-if="wz" :all-routes="allRoutes" @track-selected="wzFunc" @close="wz = false" />-->

<!--    <trajectoryTime v-if="drwz" :all-routes="allRoutes" @track-selected1="drwzFunc" @close="drwz = false" />-->

  </div>
</template>

<script>
import { dw } from '@fullcalendar/core/internal-common'
import maps from './maps/index.vue'
import headers from './pageModel/headers.vue'
import userList from './pageModel/index.vue'
import tip from './pageModel/tip.vue'
import trajectoryTime from './pageModel/trajectoryTime.vue'
import {getAllGpsInfo} from "@/api/gpsinfo";

export default {
  components: { maps, headers, userList, tip, trajectoryTime },
  data() {
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
    return {
      startTime: `2025-10-01 00:00:00`,
      endTime: `${todayStr} 23:59:59`,
      gpsArr: undefined,
      groupResult: undefined,
      drwzIndex: 0,
      wz: false,
      drwz: false,
      allRoutes: [
      ],
    }
  },
  mounted() {
  },
  methods: {

    wzFunc(result) {
      this.$refs.mapsRef.delArr()
      for (let i = 0; i < result.length; i++) {
        for (let j = 0; j < this.groupResult.length; j++) {
          if (result[i].trackId === this.groupResult[j].id) {
            this.$refs.mapsRef.puPoint(result[i].coord, result[i])
            console.log(result[i])
            break;
          }
        }
      }
    },
    drwzFunc(result) {
      this.$refs.mapsRef.delArr()
      this.$refs.mapsRef.puPoint(result[this.drwzIndex].coord, result[this.drwzIndex])
    },
    getGps(data){
      this.gpsArr = data
      console.log('gspArr',this.gpsArr)
    },
    getGpsInfos() {
      // 取
      const txt = JSON.parse(sessionStorage.getItem('tempGpsData'))
      console.log(txt)
      for (const userId in txt) {
        if (txt.hasOwnProperty(userId)) {
          const user = txt[userId];
          const coord = [parseFloat(user.lng), parseFloat(user.lat)];

          const trackInfo = {
            trackId: user.userid,
            time: new Date(user.time).toLocaleString(),
            coord: coord
          };

          // 调用地图组件的 puPoint 方法显示用户位置
          this.$refs.mapsRef.puPoints(coord, trackInfo);
        }
      }
    },
    GpsInfo(v, txt,data) {
      console.log('GpsInfo',v,txt,data)
      this.$refs.mapsRef.delArr()
      if (v === 'wz') {
        console.log('显示所有',txt)
        // 遍历所有用户数据并显示在地图上
        // 修改原来的 for...in 循环
        for (const userId in txt) {
          if (txt.hasOwnProperty(userId)) {
            const user = txt[userId];
            const coord = [parseFloat(user.lng), parseFloat(user.lat)];

            const remark2 = user.remark2;

            const trackInfo = {
              trackId: userId,
              time: new Date(user.time).toLocaleString(),
              coord: coord,
              realName: user.realName
            };

            // 调用地图组件的 puPoints 方法显示用户位置，并传递 remark2
            this.$refs.mapsRef.puPoints(coord, trackInfo, remark2);
          }
        }
      }
    },


      uRtn(v, txt) {
        if (v === 'wz') {
          console.log('this.gpsArr', this.gpsArr)
          console.log('传入的用户列表:', txt)

          // 验证参数
          if (!txt || !Array.isArray(txt)) {
            console.warn('txt 参数无效或未提供:', txt);
            return;
          }

          // 确保 gpsArr 已定义
          if (!this.gpsArr || !Array.isArray(this.gpsArr)) {
            console.warn('gpsArr 未初始化:', this.gpsArr);
            return;
          }

          // 清除地图上现有的标记
          this.$refs.mapsRef.delArr();

          // 遍历所有轨迹数据
          this.gpsArr.forEach(track => {
            const { trackId, points } = track;

            // 验证 points 数据
            if (!points || !Array.isArray(points) || points.length === 0) {
              console.warn('无效的 points 数据:', points);
              return;
            }

            // 获取最新位置点
            const latestPoint = points
              .sort((a, b) => new Date(b.time) - new Date(a.time))[0];

            if (!latestPoint) {
              console.warn('未能获取最新的位置点');
              return;
            }

            const coord = latestPoint.coord;

            // 安全地查找匹配用户
            const matchedUser = txt.find(user => user.account === trackId) || {};

            const pointInfo = {
              trackId: matchedUser.realName || trackId,
              time: new Date(latestPoint.time).toLocaleString(),
              coord: coord
            };

            console.log(`显示用户 ${pointInfo.trackId} 的位置:`, coord);
            this.$refs.mapsRef.puPoint(coord, pointInfo, matchedUser);
          });

          console.log(`总共显示了 ${this.gpsArr.length} 个用户的位置`);
        } else if (v === 'dw') {
        // this.$refs.mapsRef.puPoint([114.31243, 30.42462], txt)
        this.$refs.mapsRef.delArr()
        let arr = []
        arr.push([114.17464, 30.63895])
        arr.push([114.17207, 30.64293])
        arr.push([114.17001, 30.64478])
        arr.push([114.1652, 30.64951])
        arr.push([114.16451, 30.65061])
        arr.push([114.15971, 30.64928])

        arr.push([114.1543, 30.64899])
        arr.push([114.15404, 30.64375])
        arr.push([114.15379, 30.63754])
        arr.push([114.16254, 30.63592])
        arr.push([114.16872, 30.63666])
        this.$refs.mapsRef.trajectory(arr)
      } else if (v === 'drwz') {
          const txtData = JSON.parse(sessionStorage.getItem('tempGpsData'));
          console.log('txt1111', txt);

          // 先从缓存中查找
          if (txtData && txt.phone) {
            const userData = txtData[txt.phone];

            if (userData) {
              this.$refs.mapsRef.delArr();
              console.log('缓存中的用户数据', userData);

              const coord = [parseFloat(userData.lng), parseFloat(userData.lat)];
              const txt1 = {
                trackId: txt.name,
                time: new Date(userData.time).toLocaleString(),
                coord: coord
              };
              this.$refs.mapsRef.puPoint(coord, txt1, userData);
              return;
            } else {
              console.log('未找到对应手机号的缓存数据，将调用接口获取');
            }
          } else {
            console.log('缓存中未找到GPS数据或手机号无效，将调用接口获取');
          }

          // 如果缓存中未找到数据，则调用接口获取
          const startTimestamp = new Date(this.startTime).getTime();
          const endTimestamp = new Date(this.endTime).getTime();

          getAllGpsInfo(txt.phone, startTimestamp, endTimestamp).then(res => {
            this.$refs.mapsRef.delArr();
            console.log(res.data);
            // 假设 res.data 是你获取到的数据数组
            const latestData = res.data.sort((a, b) => b.time - a.time)[0]; // 按时间降序排序并取第一条
            console.log('latestData', latestData);
            if (latestData) {
              const coord = [parseFloat(latestData.lng), parseFloat(latestData.lat)];
              const txt1 = {
                // trackId: latestData.userid,
                trackId: txt.name,
                time: new Date(latestData.time).toLocaleString(),
                coord: coord
              };
              this.$refs.mapsRef.puPoint(coord, txt1, latestData);
            } else {
              console.log('接口未返回有效数据');
            }
          }).catch(() => {
            console.log('获取GPS信息失败');
          });
      }

    },
    AddGuiji() {
      let arr = []
      arr.push([114.29287, 30.62107])
      arr.push([114.29918, 30.62646])
      arr.push([114.38278, 30.68251])
      arr.push([114.39754, 30.66184])
      arr.push([114.42432, 30.60778])
      arr.push([114.37145, 30.58768])
      this.$refs.mapsRef.trajectory(arr)
    },
    ViewGuiji(index, startTime = null, endTime = null,realName) {
      const route = this.allRoutes[index];
      console.log('route',route)
      if (!route) {
        console.error("无效的路线索引:", index);
        return;
      }

      // 提取基础信息
      const { trackId, startTime: routeStartTime } = route;
      let pointsForMap;
      let timeArray;

      if (Array.isArray(route.points) && route.points.length > 0) {
        let filteredPoints = route.points;

        // 如果提供了时间范围，则进行筛选
        if (startTime && endTime) {
          const start = new Date(startTime);
          const end = new Date(endTime);

          filteredPoints = route.points.filter(point => {
            const pointTime = new Date(point.time);
            return pointTime >= start && pointTime <= end;
          });

          if (filteredPoints.length === 0) {
            console.warn("指定时间段内没有轨迹点");
            return;
          }
        }

        // 判断数据格式
        if (filteredPoints[0].coord && Array.isArray(filteredPoints[0].coord)) {
          // 新格式：包含 coord 和 time
          pointsForMap = filteredPoints.map(point => point.coord);
          timeArray = filteredPoints.map(point => point.time);
          console.log("使用新格式数据，已转换 points");
        } else if (Array.isArray(filteredPoints[0]) && filteredPoints[0].length === 2) {
          // 旧格式：直接就是 [lng, lat]
          pointsForMap = filteredPoints;
          console.log("使用旧格式数据");
        } else {
          console.error("points 数据格式不正确:", filteredPoints);
          return;
        }
      } else {
        console.error("points 不是有效的数组或为空");
        return;
      }

      // 调用地图组件方法
      this.$refs.mapsRef.trajectory(pointsForMap, trackId, realName,routeStartTime || startTime);
      this.$refs.mapsRef.trajectoryCreatePointList(pointsForMap, timeArray);
    },
    // handleTimeFilter(startTime, endTime, trackId) {
    //   // 根据 trackId 找到对应的轨迹数据
    //   const route = this.allRoutes.find(r => r.trackId === trackId);
    //   if (!route) {
    //     console.error("未找到轨迹数据:", trackId);
    //     return;
    //   }
    //
    //   // 筛选时间段内的轨迹点
    //   const filteredPoints = route.points.filter(point => {
    //     const pointTime = new Date(point.time);
    //     const start = new Date(startTime);
    //     const end = new Date(endTime);
    //     return pointTime >= start && pointTime <= end;
    //   });
    //
    //   // 如果有筛选结果，则在地图上显示
    //   if (filteredPoints.length > 0) {
    //     this.$refs.mapsRef.delArr(); // 清除现有轨迹
    //
    //     // 提取坐标数组用于地图显示
    //     const pointsForMap = filteredPoints.map(point => point.coord);
    //     console.log(pointsForMap, "123123");
    //
    //     // 在地图上绘制筛选后的轨迹
    //     this.$refs.mapsRef.trajectory(pointsForMap, trackId, startTime);
    //
    //     // 创建轨迹点列表
    //     const timeArray = filteredPoints.map(point => point.time);
    //     console.log(timeArray, "123123");
    //
    //     this.$refs.mapsRef.trajectoryCreatePointList(pointsForMap, timeArray);
    //   } else {
    //     console.warn("指定时间段内没有轨迹点");
    //   }
    // },

    // 添加接收子组件传来的时间筛选事件
    // onTimeRangeSelected(startTime, endTime, trackId) {
    //   this.handleTimeFilter(startTime, endTime, trackId);
    // },

    onTrackSelected(index, startTime = null, endTime = null) {
      this.$refs.mapsRef.delArr();
      this.ViewGuiji(index, startTime, endTime);
    },

    onTrackSelectedU(txt,tableData) {
      console.log('showMap后返回txt',txt,tableData);

      // 数据转换
      if (tableData && Array.isArray(tableData) && tableData.length > 0) {
        // 提取用户ID（假设所有数据的userid相同）
        const trackId = tableData[0].userid;

        // 转换数据格式
        const points = tableData.map(item => {
          return {
            coord: [parseFloat(item.lng), parseFloat(item.lat)],
            time: this.formatTimestamp(item.time) // 格式化时间戳
          };
        }).reverse();

        // 构造目标格式数据
        const convertedData = {
          trackId: trackId,
          points: points
        };

        console.log('转换后的数据:', convertedData);

        // 查找是否已有相同 trackId 的记录
        const existingIndex = this.allRoutes.findIndex(route => route.trackId === convertedData.trackId);

        if (existingIndex !== -1) {
          // 如果找到了，替换原有数据
          this.allRoutes.splice(existingIndex, 1, convertedData);
        } else {
          // 否则新增数据
          this.allRoutes.push(convertedData);
        }


        console.log('转换后的数据:', this.allRoutes);

      }

      let index = null;
      this.$refs.mapsRef.delArr();
      for (let i = 0; i < this.allRoutes.length; i++) {
        console.log('this.allRoutes[i].trackId',this.allRoutes[i].trackId);
        if (this.allRoutes[i].trackId === txt.phone) {
          index = i;
          this.ViewGuiji(index,null,null,txt.name)
          break;
        }
        // for (let j = 0; j < txt.length; j++) {
        //   if (this.allRoutes[i].trackId === txt[j].id) {
        //     console.log('txtAndallRoutes', this.allRoutes[i].trackId === txt[j].id);
        //
        //     this.ViewGuiji(j)
        //   }
        // }
      }
    },

    formatTimestamp(timestamp) {
      if (!timestamp) return '';
      // 处理毫秒级时间戳
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    play(v) {
      console.log(v)
      if (v === 'clear') {
        this.$refs.mapsRef.delArr()
        return
      }
      this.$refs.mapsRef.trajectoryStartAndStop(v)
    },

    group(v){
      if (v === 'clear') {
        this.$refs.mapsRef.delArr()
        return
      }
    },

    /*框选回调*/
    mapsArr(arr) {
      console.log(arr,'arr')
      this.$refs.userListRef.mapSetUser(arr)
    }
  }
}
</script>
<style lang="scss" scoped>
* {
  color: #606266;
  font-size: 13px;
}

.pages {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  position: relative;

  .cener {
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: all;
    z-index: 999;
  }
}
</style>
